<template>
	<div>
		<el-tabs v-model="name">
			<el-tab-pane label="登录" name="first">
				<el-form :model="loginData" label-width="120px">
					<el-form-item label="账号：">
						<el-input v-model="loginData.user" />
					</el-form-item>
					<el-form-item label="密码：">
						<el-input v-model="loginData.pwd" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmitLogin">登录</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="注册" name="second">
					<el-form :model="registData" label-width="120px">
					<el-form-item label="账号：">
						<el-input v-model="registData.user" />
					</el-form-item>
					<el-form-item label="密码：">
						<el-input v-model="registData.pwd" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmitRegist">注册</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
		</el-tabs>
	</div>

</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { RootState } from '@/store'
import { useRouter }  from 'vue-router'
const store = useStore<RootState>()
const router = useRouter()
const name = ref('first')
// do not use same name with ref
const loginData = reactive({
	user: '',
	pwd: ''
})

const registData = reactive({
	user: '',
	pwd: ''
})

const onSubmitLogin = async () => {
	const resp = await request.post('/api/login', loginData)
	const { code, message, data, token } = resp.data;
	if(code === 200) {
		localStorage.setItem('token', token);
		store.commit('SET_USER', { isLogin: true, token: token, nickname: data.nickname })
		router.push({  name: 'home' })
		ElMessage({ type: 'success', message })
	} else {
		ElMessage({ type: 'error', message })
	}
}

const onSubmitRegist = async () => {
	const resp = await request.post('/api/regist', registData)
	const { code, message } = resp.data;
	if(code === 200) {
		ElMessage({ type: 'success', message })
	} else {
		ElMessage({ type: 'error', message })
	}
}
</script>
